<?php
class CompCmsComponent extends Object {
	var $components = array( 'Auth','Session','RequestHandler','Email','Cookie','CompCms');
	
	var $cms_files = array('Cm.id','Cm.controller','Cm.action','Cm.name','Cm.keywords','Cm.description');
	var $cms_section_files = array('CmsSection.id','CmsSection.cms_id','CmsSection.body','CmsSection.status');
	var $page = null;
	var $sections = null;
	
	public function initialize(&$controller) {
        $this->controller = $controller;
        $this->data = $controller->data;  	
    }
    
    /**
         * Page title and content for sections
         */
    public function get(){
    	if(is_array($this->_page())){			
			if(isset($this->page['Cm']['name'])){
				$this->controller->set('title_for_layout_cms',$this->page['Cm']['name']);
				$this->controller->set('keywords_for_layout_cms',$this->page['Cm']['keywords']);
				$this->controller->set('description_for_layout_cms',$this->page['Cm']['description']);
			
				if(!$this->_sections()){
					$this->controller->set('sections',$this->sections);
				}
			}
			
		}else{
			$this->controller->set('title_for_layout_cms',false);
			$this->controller->set('keywords_for_layout_cms',false);
			$this->controller->set('description_for_layout_cms',false);
		} 
    }
    
    /**
     * 
     * Get current page title and keywords
     */
    private function _page(){
    	switch($this->controller->params['controller']){
    		case 'pages':
    			$this->page = $this->controller->Cm->find('first',
					array(
						'conditions'=>
							array('Cm.controller = ' => $this->controller->params['controller'],
								'Cm.action = ' => $this->controller->params['pass'][0]
						)
						,'fields'=>$this->cms_files
					));
				break;
				
    		default:
		    	$this->page = $this->controller->Cm->find('first',
					array(
						'conditions'=>
							array('Cm.controller = ' => $this->controller->params['controller'],
								'Cm.action = ' => $this->controller->params['action']
						)
						,'fields'=>$this->cms_files
					));    			
    	}

			
		return (is_array($this->page) && !empty($this->page)) ? $this->page : false;
    }
    
    /**
     * 
     * Get current sections content
     */
    private function _sections(){
		$this->sections = $this->controller->CmsSection->find('all',
			array(
				'conditions'=>
					array('CmsSection.cms_id = '=>$this->page['Cm']['id'])
				,'fields'=>$this->cms_section_files
			));
		return (is_array($this->sections) && !empty($this->sections)) ? $this->sections : false;
    }    
}